//
//  BarChartView.m
//  FindJob
//
//  Created by 233 on 16/3/7.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "BarChartView.h"
#import "BarView.h"

@interface BarChartView ()
@property(nonatomic,strong)UIView *lineView;
@end

@implementation BarChartView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        _leftSpacing = 5;
        _rightSpacing = 5;
        _barsSpacing = 20;
        self.layer.masksToBounds = YES;
        [self addSubview:self.lineView];
    }
    return self;
}
- (void)reloadDatas{
    if (_dataSource == nil) {
        NSLog(@"必须给dataSource赋值");
        return;
    }
    
    NSInteger numbers = [self.dataSource numberOfBarsInBarChartView:self];
    CGRect barFrame = CGRectZero;
    CGFloat barWith = (self.frame.size.width - self.leftSpacing - self.rightSpacing - (numbers - 1) * self.barsSpacing) / numbers;
    for (int i = 0; i < numbers; i++) {
        barFrame =  CGRectMake(self.leftSpacing + (barWith + self.barsSpacing) * i  , 0, barWith, self.frame.size.height);
        
        BarView *barView = [[BarView alloc] initWithFrame:barFrame];
        BarModel
        *barModel = [self.dataSource barChartView:self barModelInRow:i];
        barView.titleLabel.text = barModel.title;
        barView.subTitleLabel.text = [NSString stringWithFormat:@"%.f",barModel.value];
        barView.barColor = barModel.barColor;
        
        CGFloat reslutValue = barModel.value;
        if (barModel.value > self.maxValue) {
            reslutValue = self.maxValue;
        }
        if (barModel.value < self.minValue) {
            reslutValue = self.minValue;
        }
        barView.grade = reslutValue / self.maxValue;
        [self addSubview:barView];
        [barView updateViews];
    }
    
    CGRect frame = self.lineView.frame;
    self.lineView.frame = CGRectMake(0, self.frame.size.height - 1, 0, 1);
    [UIView animateWithDuration:1.0f animations:^{
        self.lineView.frame = frame;
    }];
}
#pragma mark -- getters
- (UIView *)lineView{
    if (!_lineView) {
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 1, self.frame.size.width, 1)];
        _lineView.backgroundColor = [UIColor orangeColor];
    }
    return _lineView;
}
@end
